<template>
  <AdminHeader />
  <div v-if="showPageContent" class="container-fluid">
    <div class="row text-center justify-content-center webtitle"></div>
    <div class="row justify-content-center">
      <el-form ref="chapterForm" :model="form" label-width="auto" @submit.prevent="updateUser" style="max-width: 90%;">
        <el-form-item label="用户名：">
          <el-input v-model="form.username" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="用户昵称：">
          <el-input v-model="form.nickname" clearable required></el-input>
        </el-form-item>
        <el-form-item label="用户介绍：">
          <el-input type="textarea" v-model="form.introduce" required></el-input>
        </el-form-item>
        <el-form-item label="登录密码：">
          <el-input v-model="form.password" placeholder="不修改就留空"></el-input>
        </el-form-item>
        <div class="twobtn">
          <el-button type="primary" native-type="submit">提交</el-button>
          <el-button @click="goBack">返回</el-button>
        </div>
      </el-form>


    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, reactive} from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElNotification } from 'element-plus';
import AdminHeader from "@/components/AdminHeader.vue";
import VueCookies from "vue-cookies";
import config from "../../../config/config.js";

const showPageContent = ref(true);
const router = useRouter();
const userId = router.currentRoute.value.params.userId;
const form = reactive({
  nickname: '',
  introduce: '',
  username: '',
  password: '',
})
const userToken = ref('');
const adminToken = VueCookies.get('adminToken');


const goBack = () => {
  router.back();
};
// 从服务器获取用户和小说信息
const fetchUserInfo = async () => {
  const apiUrl = `${config.apiUrl}/user/search?username=${userId}&type=3`;

  try {
    const getuinfo = await axios.get(apiUrl, {
      headers: {
        'Authorization': `Bearer ${adminToken}` // 使用 Cookie 中的 Token
      },
    });
    const userInfo = getuinfo.data[0];
    form.nickname = userInfo.nickname;
    form.username = userInfo.username;
    form.introduce = userInfo.introduce;

    //get userToken
    const loginres = await axios.post(`${config.apiUrl}/user/login`, {
      username: userInfo.username,
      password: userInfo.password,
    });

    if (loginres.data.token) {
      // 如果登录成功，存储 token 在 cookie 中，过期时间为 10 天
      userToken.value = loginres.data.token;
      //console.log(userToken.value);
    }

  } catch (error) {
    ElNotification({
      message: '获取用户信息失败',
      type: 'error',
      duration: 1000
    });
    goBack();
  }
};

const updateUser = async () => {

  const requestBody = {
    nickname: form.nickname,
    introduce: form.introduce,
    password: form.password,
  };

  if (form.password && form.password.trim() !== '') {
    if(form.password.length<6){
      ElNotification({
        message: '修改的密码不得少于六位！',
        type: 'error',
        duration: 2000
      });
      return;
    }
  }

  try {
    await axios.post(`${config.apiUrl}/user/update`, requestBody, {
      headers: {
        'Authorization': `Bearer ${userToken.value}`
      },
    });

    // 更新用户信息并关闭弹窗
    //userInfo.value = { ...requestBody }; // 解构并更新用户信息
    await fetchUserInfo();
    ElNotification({
      message: '用户信息更新成功！',
      type: 'success',
      duration: 1000
    });

  } catch (error) {
    ElNotification({
      message: '用户信息更新失败！',
      type: 'error',
      duration: 1000
    });
  }
};

onMounted(fetchUserInfo);
</script>

<style scoped>
.webtitle {
  font-size: 15px;
  padding: 10px;
}
.twobtn{
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}
</style>
